<template>
  <a-modal v-model:open="open" :title="isEdit ? $t('编辑') : $t('New')" @afterClose="handleClose" :maskClosable="false">
    <a-spin :spinning="spinning">
      <a-form ref="formRef" :model="formState" name="basic" v-bind="{
        labelCol: { span: 5 },
      }" :rules="rules">
        <a-form-item :label="$t('nameEn')" name="nameEn">
          <a-input v-model:value="formState.nameEn" />
        </a-form-item>
        <a-form-item :label="$t('nameZh')" name="nameZh">
          <a-input v-model:value="formState.nameZh" />
        </a-form-item>
        <a-form-item :label="$t('nameAr')" name="nameAr">
          <a-input v-model:value="formState.nameAr" />
        </a-form-item>
        <a-form-item :label="$t('显示状态')" name="visible">
          <a-radio-group v-model:value="formState.visible">
            <a-radio :value="1"> {{ $t("显示") }}</a-radio>
            <a-radio :value="0"> {{ $t("隐藏") }}</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item :label="$t('菜单状态')" name="status">
          <a-radio-group v-model:value="formState.status">
            <a-radio :value="1">{{ $t("正常") }}</a-radio>
            <a-radio :value="0">{{ $t("停用") }}</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item :label="$t('路径名')" name="menuKey">
          <a-input v-model:value="formState.menuKey" />
        </a-form-item>
        <a-form-item :label="$t('路径')" name="path">
          <a-input v-model:value="formState.path" />
        </a-form-item>
        <a-form-item :label="$t('组件')" name="component" :placeholder="$t('componentName')">
          <a-input v-model:value="formState.component" />
        </a-form-item>
        <a-form-item :label="$t('icon')" name="icon">
          <a-input v-model:value="formState.icon" />
        </a-form-item>
        <a-form-item :label="$t('序号')" name="sort">
          <a-input v-model:value="formState.sort" />
        </a-form-item>

        <a-form-item :label="$t('上级菜单')" name="parentId">
          <a-cascader v-model:value="formState.parentId" :options="options" :fieldNames="{
            label: isEn
              ? 'nameEn'
              : isCn
                ? 'nameZh'
                : isArabic
                  ? 'nameAr'
                  : 'nameEn',
            value: 'id',
            children: 'children'
          }" change-on-select />
        </a-form-item>
        <a-form-item :label="$t('备注')" name="remark">
          <a-input v-model:value="formState.remark" />
        </a-form-item>
      </a-form>

    </a-spin>
    <template #footer>
      <a-button key="back" @click="handleClose">{{ $t("关闭") }}</a-button>
      <a-button key="submit" type="primary" :loading="loading" @click="submit">{{ $t("保存") }}</a-button>
    </template>
  </a-modal>
</template>
<script lang='ts' setup>
import { useI18n } from "vue-i18n";
import { message } from "ant-design-vue";
import { queryMenus } from "@/api/setting";
import { GenItem, AddItem } from "./item-data";
import { useLanguage } from "@/hooks/index";
import { AddMenu, EditMenu } from "@/api/setting";
import { list2Tree } from "@/utils/common/common";
const { isEn, isCn, isArabic } = useLanguage();
const { t: $t } = useI18n();
const loading = ref(false);
const formRef = ref(null);
let spinning = ref(false)
let options = ref([]);
const emit = defineEmits(["ok", "close", "update:visible"]);
const props = defineProps({
  visible: {
    type: Boolean,
    required: true,
    default: false,
  },
  target: {
    type: Object,
    required: true,
    default: () => { },
  },
});
const open = computed({
  get() {
    return props.visible;
  },
  set(value) {
    emit("update:visible", value);
  },
});
const formState = ref(new GenItem());
const rules = {
  // parentId: [{ required: true, message: $t('请选择'), trigger: ['blur', 'change'] }],
  type: [
    { required: true, message: $t("请选择"), trigger: ["blur", "change"] },
  ],
  nameZh: [
    { required: true, message: $t("请输入"), trigger: ["blur", "change"] },
  ],
  nameEn: [
    { required: true, message: $t("请输入"), trigger: ["blur", "change"] },
  ],
  nameAr: [
    { required: true, message: $t("请输入"), trigger: ["blur", "change"] },
  ],
  path: [
    { required: true, message: $t("请输入"), trigger: ["blur", "change"] },
  ],
  menuKey: [
    { required: true, message: $t("请输入"), trigger: ["blur", "change"] },
  ],
  sort: [
    { required: true, message: $t("请输入"), trigger: ["blur", "change"] },
  ],
  component: [{ required: true, message: $t('请输入'), trigger: ['blur', 'change'] }]
};
const isEdit = computed(() => {
  if (isEmpty(props.target)) return false;
  return true;
});
const getAllMenus = async () => {
  const { data } = await queryMenus().finally(() => {
    loading.value = false;
  });
  options.value = list2Tree(data) ?? []
  console.log('子', options.value)
};
const setValue = () => {
  setTimeout(() => {
    formState.value = cloneDeep(props.target);
    const trees = cloneDeep(options.value)
    // 获取所有的父id
    formState.value.parentId = getPathByKey(formState.value.id, trees)
    console.log('sada', formState.value.parentId)
    spinning.value = false
  }, 2000)
}
watch(
  () => open,
  (newVal, oldVal) => {
    getAllMenus();
    if (newVal.value && props.target?.id) {
      spinning.value = true
      setValue()
    } else {
      formState.value = new GenItem();
    }
  },
  {
    deep: true,
    immediate: true,
  }
);
const getPathByKey = (curKey: number, data: []) => {
  /** 存放搜索到的树节点到顶部节点的路径节点 */
  let result = []
  /**
   * 路径节点追踪
   * @param {*} curKey 树节点标识的值
   * @param {array} path 存放搜索到的树节点到顶部节点的路径节点
   * @param {*} data 树
   * @returns undefined
   */
  let traverse = (curKey, path, data) => {
    // 树为空时，不执行函数
    if (data.length === 0) {
      return;
    }

    // 遍历存放树的数组
    for (let item of data) {
      // 遍历的数组元素存入path参数数组中
      path.push(item);
      // 如果目的节点的id值等于当前遍历元素的节点id值
      if (item.id === curKey) {
        // 把获取到的节点路径数组path赋值到result数组
        path.forEach((i:any) => {
          result.push(i.id)
        })
        return;
      }

      // 当前元素的children是数组
      const children = Array.isArray(item.children) ? item.children : [];
      // 递归遍历子数组内容
      traverse(curKey, path, children);
      // 利用回溯思想，当没有在当前叶树找到目的节点，依次删除存入到的path数组路径
      path.pop();
    }
  };
  traverse(curKey, [], data);
  // 返回找到的树节点路径
  result.pop()
  return result;
};
const submit = debounce(async () => {
  formRef.value
    .validate()
    .then(async () => {
      const data = cloneDeep(formState.value);
      if (Array.isArray(data.parentId)) data.parentId = data.parentId[data.parentId.length - 1];
      if (!data.parentId) data.parentId = 0;
      // 自定义处理部分
      loading.value = true;
      if (isEdit.value) {
        await EditMenu(formState.value.uuid, data).finally(() => {
          loading.value = false;
        });
      }
      if (!isEdit.value) {
        await AddMenu(data).finally(() => {
          loading.value = false;
        });
      }
      message.success($t("操作成功"));
      handleOk();
    })
    .catch((error: any) => {
      // consolelog("error", error);
    });
}, 1000);
//
// 自定义业务处理
//
const resetForm = () => {
  formRef.value.resetFields();
};
const clearValidates = () => {
  formRef.value.clearValidate();
};
const handleOk = () => {
  clearValidates();
  resetForm();
  emit("ok", (open.value = false));
};
const handleClose = () => {
  clearValidates();
  resetForm();
  emit("update:visible", false);
};
</script>
<style lang='scss' scoped>
@include form-item-space;
</style>